/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.eclass.servlet.front;

import cn.eclass.bean.api.IUserBean;
import cn.eclass.entity.UserEntity;
import cn.eclass.servlet.ActionFace;
import cn.eclass.utils.BeanFactory;
import cn.eclass.utils.ConstantsConf;
import cn.eclass.utils.Helper;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;

/**
 *
 * @author fortruth
 */
public class User extends ActionFace {

    IUserBean bean = BeanFactory.factory.getUserBean();
    private static final String INDEX_PAGE = "do";
    private static final String LOGIN_PAGE = "login.jsp";

    public void doLogin() throws IOException {
        String username = request.getParameter("username");
        String password = Helper.Md5(request.getParameter("password"));
        UserEntity user = bean.login(username, password);
        Map result = new HashMap();

        //Todo
        if (password.equals(user.getPassword())) {
            session.setAttribute(ConstantsConf.SESSION_USERNAME, username);
            result.put("status", "success");
            result.put("username", username);
            result.put("points", user.getPoints());
        } else {
            result.put("status", "failed");
        }
        out.print(new Gson().toJson(result));
    }

    public void doFormLogin() {
        try {
            String username = request.getParameter("username");
            String password = Helper.Md5(request.getParameter("password"));
            UserEntity user = bean.login(username, password);
            String redView = null;
            if (password.equals(user.getPassword())) {
                session.setAttribute(ConstantsConf.SESSION_USERNAME, username);
//	            request.removeAttribute("redirect");
//	            request.removeAttribute("action");
//	            request.removeAttribute("module");
                redView = "do?module=" + request.getParameter("redirect");
                response.sendRedirect(redView);
            } else {
                request.setAttribute("retry", true);
                redView = "/login.jsp?";
                request.getRequestDispatcher(redView).forward(request, response);
            }
        } catch (ServletException ex) {
            logger.error(ex);
        } catch (IOException ex) {
            logger.error(ex);
        }
    }

    public void doFormRegister() {
        try {
            UserEntity userEntity = new UserEntity();
            String username = request.getParameter("username");
            userEntity.setUsername(Helper.toUTF8(request.getParameter("username")));
            userEntity.setEmail(Helper.toUTF8(request.getParameter("email")));
            userEntity.setPassword(Helper.Md5(request.getParameter("password")));
            //userEntity.setTelephone(Helper.toUTF8(request.getParameter("telephone")));
            //userEntity.setPoints(Integer.valueOf(request.getParameter("points")));
            userEntity = bean.add(userEntity);
            String errorMsg = "";
            String redView = null;

            if (userEntity.getId() > 0) {
                session.setAttribute(ConstantsConf.SESSION_USERNAME, username);
                redView = INDEX_PAGE;
            } else {
                request.setAttribute("retry", true);
                redView = "/login.jsp?";
            }
            request.getRequestDispatcher(redView).forward(request, response);
        } catch (ServletException ex) {
            logger.error(ex);
        } catch (IOException ex) {
            logger.error(ex);
        }
    }

    public void doLogout() throws IOException {
        String redView = "do";
        String redirectModule = request.getParameter("redirect");
        if (redirectModule != null && redirectModule.length() != 0) {
            redView = "do?module=" + redirectModule;
        }
        session.removeAttribute(ConstantsConf.SESSION_USERNAME);
        session.removeAttribute(ConstantsConf.REQUEST_USERENTITY);
        if (user != null) {
            user.setLastLoginTime(System.currentTimeMillis());
            bean.update(user);
        }
        response.sendRedirect(redView);
    }

    public void doUpdate() {
        Map<String, String> result = new HashMap<String, String>();

        int userId = Integer.parseInt(request.getParameter("userId"));
        UserEntity userEntity = bean.get(userId);

        String userName = request.getParameter("username");
        if (userName != null) {
            userEntity.setUsername(Helper.toUTF8(userName));
        }
        String email = request.getParameter("email");
        if (email != null && !email.trim().equals("")) {
            userEntity.setEmail(email);
        }
        String phone = request.getParameter("phone");
        if (phone != null && !phone.trim().equals("")) {
            userEntity.setTelephone(phone);
        }
        String psw = request.getParameter("password");
        String oriPsw = Helper.Md5(request.getParameter("oriPsw"));
        if(!oriPsw.equals(userEntity.getPassword())) {
        	result.put("msg", "原密码不正确");
        	result.put("status","failed");
            out.print(new Gson().toJson(result));
        }
        if (psw != null && !psw.trim().equals("")) {
            userEntity.setPassword(Helper.Md5(psw));
        }
        bean.update(userEntity);

        result.put("status", "success");
        out.print(new Gson().toJson(result));
    }

    public void doRegister() {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(Helper.toUTF8(request.getParameter("username")));
        userEntity.setEmail(Helper.toUTF8(request.getParameter("email")));
        userEntity.setPassword(Helper.Md5(request.getParameter("password")));
        //userEntity.setTelephone(Helper.toUTF8(request.getParameter("telephone")));
        //userEntity.setPoints(Integer.valueOf(request.getParameter("points")));
        userEntity = bean.add(userEntity);

        if (userEntity.getId() > 0) {
            echoAjaxSuccess("success");
        } else {
            echoAjaxError("error");
        }
    }

    public void doCheckusername() {
        String username = request.getParameter("username");
        UserEntity user = bean.getByName(username);
        if (null != user) {
            echoAjaxSuccess("");
        } else {
            echoAjaxError("user not exist");
        }
    }

    @Override
    public void doIndex() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
